import {RouteRecordRaw, createRouter, createWebHistory, Router} from "vue-router";
import LoginView from "../views/LoginView.vue";
import HomeView from "../views/HomeView.vue";
import {MainStore} from "../store/MainStore.ts";
import {TagViewStore} from "@/store/TagsStore.ts";
import {MenuTree} from "../type/MenuTree.ts";
import ProfileView from "../views/ProfileView.vue";
import DashBoard from "../views/DashBoard.vue";
import {TagData} from "@/type/TagData.ts";


const routes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'login',
        component: LoginView,
        meta:{
            showInTagsView: false
        }
    },

    {
        path: '/',
        name: 'home',
        component: HomeView,
        redirect: '/dashboard',
        meta: {
            isShow: true
        },
        children: [
            {
                path: '/dashboard',
                name: 'dashboard',
                component: DashBoard,
                meta: {
                    keepAlive: true
                }
            },
            {
                path: '/profile',
                name: 'profile',
                component: ProfileView
            }
        ]
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes: routes
});


router.beforeEach( (to, _, next) => {



    const mainStore = MainStore()
    const tagsViewStore = TagViewStore()

    if (!sessionStorage.getItem('isLogin') && to.path !== '/login'){
        next('/login')
    }else {
        if (!mainStore.asyncRoutesMark && sessionStorage.getItem('isLogin')){

            const menusJsonString = sessionStorage.getItem('menu');
            if (menusJsonString != null){
                const menus = JSON.parse(menusJsonString) as MenuTree[]
                parseMenuTree(router, menus[0]).then()
                mainStore.asyncRoutesMark = true
            }



            next({...to, replace: true})
        }else {
            if (to.meta.showInTagsView !== false) {
                if (!tagsViewStore.visitedViews.some((v) => v.name === to.name)){
                    tagsViewStore.addView({name: to.name, path: to.path} as TagData);
                }
            }
            next()
        }
    }
} )

const modules = import.meta.glob('../views/**/*.vue')
async function parseMenuTree(router: Router, menuTree: MenuTree) {


    router.addRoute('home', {
        path: menuTree.url,
        name: menuTree.name,
        component: modules[`../views/${menuTree.component}.vue`]
    })


    const children = menuTree.children


    if (children !== undefined && children.length !== 0) {
        for (const child of children){
            await parseMenuTree(router, child)
        }
    }
}



export default router;